import type { FC, ReactNode } from 'react'
import React, { memo, useState } from 'react'
import { Button, message } from 'antd'
import { ButtonWrapper } from '@/components/verify-code-button/style'
import { emailReg, phoneReg, Status, VerifyType } from '@/global/constant'
import { useMyDispatch } from '@/store'
import {
  changeIsCountingAction,
  fetchVerifyCodeAction
} from '@/store/module/app'
import { IGetCode } from '@/global/type'

interface IProps {
  children?: ReactNode
  onClick: () => IGetCode | void
}

const VerifyCodeButton: FC<IProps> = (props) => {
  const { onClick } = props
  const dispatch = useMyDispatch()
  // 获取验证码
  const [isCounting, setIsCounting] = useState(false)
  const [currentMsg, setCurrentMsg] = useState('获取验证码')

  /**
   * 这里已经封装好了发送验证码的逻辑,父传子的onClick函数里面只需要返回config就行了，
   * 这里会根据配置决定是发送 邮件验证码 还是 手机验证码
   */
  function getCodeClick() {
    const config = onClick()
    if (typeof config !== 'object') return
    // 手机和邮箱的校验规则
    const { type, data } = config
    const currentReg = type === VerifyType.Phone ? phoneReg : emailReg
    const currentMsg =
      type === VerifyType.Phone ? '请输入有效的手机号' : '请输入有效的邮箱'
    if (!currentReg.test(data)) {
      message.error(currentMsg)
      return
    }
    // 通过校验，正式发请求
    dispatch(fetchVerifyCodeAction(config)).then(({ payload: code }) => {
      if (code === Status.SUCCESS) {
        setIsCounting(true)
        dispatch(changeIsCountingAction(true))

        let count = 60
        const timer = setInterval(() => {
          if (count === 0) {
            setIsCounting(false)
            dispatch(changeIsCountingAction(false))
            setCurrentMsg('获取验证码')
            clearInterval(timer)
            return
          }
          setCurrentMsg(`${--count}s`)
        }, 1000)
      }
    })
  }

  return (
    <ButtonWrapper>
      <Button
        onClick={getCodeClick}
        disabled={isCounting}
        className="code-btn"
        type="text"
      >
        {currentMsg}
      </Button>
    </ButtonWrapper>
  )
}

export default memo(VerifyCodeButton)
